package br.com.massai.controller.filter;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import br.com.massai.model.dao.ControleAcessoDAO;
import br.com.massai.model.dao.UsuarioDAO;
import br.com.massai.model.entity.Privilegio;
import br.com.massai.model.entity.Url;
import br.com.massai.model.entity.Usuario;
import br.com.massai.view.enums.PerfilEnum;
import br.com.massai.view.enums.RoleEnum;
import br.com.massai.view.utils.FacesUtil;
import br.com.massai.view.utils.NavigationUtil;

@Named("controleAcesso")
@SessionScoped
public class SessionControl implements Serializable {

	private static final long serialVersionUID = -2419787857887789936L;

	private Usuario usuario;
	private List<Url> urls;

	@Inject private UsuarioDAO usuarioDAO;
	@Inject private ControleAcessoDAO controleAcessoDAO;

	public SessionControl() { }

	public HttpSession obterSession(){
		return (HttpSession) FacesUtil.obterFacesContext().getExternalContext().getSession(false);
	}

	public Usuario login(String login, String senha) throws Exception{
		try {
			usuario = usuarioDAO.obterCredenciais(login, senha);
			if(usuario != null){
				usuario.setControleAcesso(controleAcessoDAO.obterUltimoAcesso(usuario));
				controleAcessoDAO.addControleAcessoLogin(usuario);
				carregaUrls();
			}
			return usuario;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}
	
	private void carregaUrls(){
		if(usuario != null && usuario.getId() != null){
			urls = new ArrayList<Url>();
			for(Privilegio p : usuario.getPrivilegios())
				for(Url u : p.getUrls())
					urls.add(u);
		}
	}

	public List<Url> urlsAcesso(){
		if(getUsuario() != null)
			return getUrls();
		return new ArrayList<Url>();
	}

	public void logout() throws IOException {
		invalidateSession();
		NavigationUtil.toLogin();
	}
	
	public String nomeUsuarioLogado(){
		if(loggedIn())
			return getUsuario().getNome();
		return null;
	}

	public static void invalidateSession(){
		FacesUtil.obterFacesContext().getExternalContext().invalidateSession();
	}

	public boolean loggedIn(){
		return usuario != null;
	}

	public PerfilEnum perfilLogado(){
		return null;
	}

	public boolean exibeFuncao(String str){
		if(usuario != null)
			if(ehAdministrador()) return true;	
			for(Privilegio p : usuario.getPrivilegios()){
				if(p.getDescricao() != null && str.trim().equals(p.getFuncao().trim())){
					return true;
				} else if(p.getModulo().getSigla() != null && str.trim().equals(p.getModulo().getSigla().trim())){
					return true;
				} else if(p.getModulo().getModuloPai() != null && p.getModulo().getModuloPai().getSigla() != null && str.trim().equals(p.getModulo().getModuloPai().getSigla().trim())){
					return true;
				}
			}
		return false;
	}

	public String ultimoAcesso(){
		if(usuario != null && usuario.getControleAcesso() != null)
			return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(usuario.getControleAcesso().getDataLogin());
		return "Primeiro Acesso";
	}

	public String ipUltimoAcesso(){
		if(usuario != null && usuario.getControleAcesso() != null)
			return usuario.getControleAcesso().getIp();
		return FacesUtil.obterIP();
	}

	public boolean ehAdministrador(){
		if(usuario != null){
			if(usuario.getRole().equals(RoleEnum.A)) return true;
		}
		return false;
	}

	public boolean isAdministrador(){
		return true;
	}

	public Usuario getUsuario(){
		return usuario;
	}

	public void setUsuario(Usuario user){
		this.usuario = user;
	}

	public List<Url> getUrls() {
		return urls;
	}

	public void setUrls(List<Url> urls) {
		this.urls = urls;
	}
}
